#include "led.h"
#include "FreeRTOS.h"
#include "task.h"
#include "./lcd/bsp_ili9341_lcd.h"
#include "usart.h"
#include "key.h"
#include "queue.h"
#include "semphr.h"
#include "stdio.h"

static TaskHandle_t appTaskCreateHandle = NULL;
static TaskHandle_t receiveTaskCreateHandle = NULL;
static TaskHandle_t sendTaskCreateHandle = NULL;

SemaphoreHandle_t binarySem_handle = NULL;

#define QUEUE_LEN 4
#define QUEUE_SIZE 4

static void App_Task(void);
static void Receive_Task(void* pvParameters);
static void Send_Task(void* pvParameters);

int main(void)
{ 
	BaseType_t xReturn = pdPASS;
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);//设置系统中断优先级分组4
	KEY_Init();
	LED_Init();		        //初始化LED端口
	ILI9341_Init();//液晶初始化    
	LCD_SetColors(BLACK,WHITE);//设置白底黑字
	LCD_SetFont(&Font8x16);//设置字体大小
	ILI9341_Clear(0,0,LCD_X_LENGTH,LCD_Y_LENGTH);//清屏
  ILI9341_GramScan ( 6 );//设置显示模式
	USART_Config(115200);
  LED_Color(LED_OFF);
	
	xReturn = xTaskCreate(
		App_Task,
	  "APP_Task",
		512,
		NULL,
		1,
	  &appTaskCreateHandle
	);
	if(pdPASS == xReturn){
		vTaskStartScheduler();          //开启任务调度
	}
  else{
		printf("Error Start RTOS\n");
	}
	
}

static void App_Task(void)
{
	BaseType_t xReturn = pdPASS;
	taskENTER_CRITICAL(); //进入临界区
	binarySem_handle = xSemaphoreCreateBinary();
	if(binarySem_handle!=NULL){
		printf("Success Create binarySem_handle\n");
	}
	
	xReturn = xTaskCreate(
		Receive_Task,
	  "Receive_Task",
		512,
		NULL,
		2,
	  &receiveTaskCreateHandle
	);
	if(pdPASS == xReturn){
		printf("Success Create ReceiveTask\n");
	}
	
	xReturn = xTaskCreate(
		Send_Task,
	  "Send_Task",
		512,
		NULL,
		3,
	  &sendTaskCreateHandle
	);
	if(pdPASS == xReturn){
		printf("Success Create SendTask\n");
	}
	vTaskDelete(appTaskCreateHandle);
	taskEXIT_CRITICAL();//退出临界区
}

static void Receive_Task(void* pvParameters)
{
	BaseType_t xReturn = pdTRUE;
	uint32_t r_queue;
	int flag=0;
	while(1){
		xReturn = xSemaphoreTake(binarySem_handle, portMAX_DELAY); /*一直等待*/
		if(pdTRUE == xReturn)
		{
			flag++;
			printf("Success get binary_sem\n",r_queue);
		}
		LED_Color(flag%8);
	}
}

static void Send_Task(void* pvParameters)
{
		BaseType_t xReturn = pdTRUE;
		while(1){
			if(KEY_Scan()== '1')
			{
				xReturn = xSemaphoreGive(binarySem_handle);
				if(xReturn == pdTRUE)
				{
					printf("Success free binary_sem\n");
				}
			}
			vTaskDelay(20);
		}
}

